package com.advertisementsystem.Interceptor;

import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.utils.AuthContextHolder;
import com.advertisementsystem.utils.JwtUtils;
import com.advertisementsystem.utils.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
@Component
@Slf4j
public class WebSocketAuthInterceptor implements HandshakeInterceptor {
    private static RedisCache redisCache;


    // Add setter for dependency injection
    @Autowired
    public void setRedisCache(RedisCache redisCache) {
        WebSocketAuthInterceptor.redisCache = redisCache;
    }
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;

            // 从URL参数中获取token
            String token = servletRequest.getServletRequest().getParameter("token");

            if (StringUtils.hasText(token)) {
                try {
                    // 验证token
                    String userId = JwtUtils.getUserIdFromToken(token);
                    String userType = JwtUtils.getUserTypeFromToken(token);
                        // 从redis中获取用户信息
                    if (userId != null) {
                        attributes.put("userId", Long.parseLong(userId));
                        attributes.put("userType", userType);
                        AuthContextHolder.setUserId(Long.parseLong(userId));
                        log.info("WebSocket连接认证成功 userId: {}, userType: {}", userId, userType);
                        return true;
                    }
                } catch (Exception e) {
                    log.error("WebSocket连接认证失败", e);
                }
            }
        }
        log.warn("WebSocket连接认证失败：token无效");
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
        // 握手后的处理
    }
}
